<script setup lang="ts">
  import { ref, watch } from 'vue';
  import {
    addarch,
    editarch,
    getCabinetDetail,
    getCrdaDetail,
  } from '@/api/archives';
  import { FormInstance, Message } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import { omit } from 'lodash';
  const formRef = ref<FormInstance | null>(null);
  const props = defineProps({
    visible: Boolean,
    formType: Array,
    params: Object,
    type: String || Number,
  });
  const { loading, setLoading } = useLoading();
  defineOptions({
    name: 'userAddSetting',
  });

  const formData = ref({
    arc_code: '', //档案编号 *
    arc_name: '', //档案名称 *
    arc_dir_code: '', //档案目录号
    arc_cate_id: '', //档案类别id *
    arc_cate_code_id: '', //档案类别号id *
    arc_store_life_id: '', //档案保管年限id *
    arc_company: '', //单位名称
    arc_year: '', //所属年份 *
    arc_month: '', //所属月份 *
    arc_cabinet_id: '', //档案柜id *
    arc_cabinet_row: '', //栏号 *
    arc_cabinet_col: '', //格号 *
    arc_sort: '', //排序
  });
  const emit = defineEmits(['update:visible', 'refresh']);

  watch(
    () => props.params,
    async (newVal) => {
      if (newVal) {
        // 请求机构详情
        const res = await getCabinetDetail({ arc_id: newVal.id });
        // 填充表单数据（安全赋值）
        Object.assign(formData.value, res.data);
        formData.value.arc_year = `${res.data.arc_year}-${res.data.arc_month}`;
      }
    },
    { immediate: true, deep: true }
  );

  const handleSubmit = async () => {
    if (!(await formRef.value?.checkForm())) {
      try {
        setLoading(true);
        const parts = formRef.value?.formModel.arc_year.split('-');
        const fidata = omit(
          formRef.value?.formModel,
          'arc_cabinet_name',
          'arc_cate_name',
          'arc_cate_cod_name',
          'arc_store_life_name',
          'arc_type_name'
        );
        const res = await editarch({
          ...fidata,
          arc_year: parts[0],
          arc_month: parts[1] ? parts[1] : fidata.arc_month,
          arc_type: props.type,
        });
        Message.success(res.msg);
        emit('update:visible', false);
        emit('refresh');
        setLoading(false);
      } catch (error) {
        setLoading(false);
      }
    } else {
      Message.error('请正确填写表单！');
    }
  };
</script>

<template>
  <a-modal
    title="编辑档案"
    :visible="visible"
    @ok="handleSubmit"
    title-align="start"
    :ok-loading="loading"
    @cancel="
      () => {
        emit('update:visible', false);
      }
    "
  >
    <pro-form
      ref="formRef"
      hiddenBtn
      :form-json="formType"
      :form-data="formData"
    ></pro-form>
  </a-modal>
</template>

<style scoped lang="less">
  :deep(.arco-select-view-inner) {
    text-align: left !important;
  }
</style>
